import _Button from "choerodon-ui/pro/lib/button";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _Select from "choerodon-ui/pro/lib/select";
import _Modal from "choerodon-ui/pro/lib/modal";
import _map from "lodash/map";
import _isEmpty from "lodash/isEmpty";
import React, { useContext, useState, useEffect } from 'react';
import { observer } from 'mobx-react-lite';
import classNames from 'classnames';
import styles from "./style/index.less?modules";
import SearchModal from "./modal";
import Store from "./stores";
import QueryBar from "./QueryBar";
import { setCondition, setOrder } from "./utils";

var modalKey = _Modal.key();

var Option = _Select.Option;
var SearchList = observer(function () {
  var _useContext = useContext(Store),
      _useContext$className = _useContext.className,
      className = _useContext$className === void 0 ? '' : _useContext$className,
      dataSet = _useContext.dataSet,
      fields = _useContext.fields,
      ignoreFields = _useContext.ignoreFields,
      _useContext$border = _useContext.border,
      border = _useContext$border === void 0 ? false : _useContext$border,
      _useContext$noCopy = _useContext.noCopy,
      noCopy = _useContext$noCopy === void 0 ? false : _useContext$noCopy,
      _useContext$noSort = _useContext.noSort,
      noSort = _useContext$noSort === void 0 ? false : _useContext$noSort,
      _useContext$noQuery = _useContext.noQuery,
      noQuery = _useContext$noQuery === void 0 ? false : _useContext$noQuery,
      _useContext$noConditi = _useContext.noCondition,
      noCondition = _useContext$noConditi === void 0 ? false : _useContext$noConditi,
      listDataSet = _useContext.listDataSet,
      searchCode = _useContext.searchCode,
      _useContext$modalProp = _useContext.modalProps,
      modalProps = _useContext$modalProp === void 0 ? {} : _useContext$modalProp;

  var _useState = useState(undefined),
      _useState2 = _slicedToArray(_useState, 2),
      listValue = _useState2[0],
      setListValue = _useState2[1];

  var _useState3 = useState(null),
      _useState4 = _slicedToArray(_useState3, 2),
      type = _useState4[0],
      setType = _useState4[1];

  var syncDataLength = listDataSet.filter(function (record) {
    return record.status === 'sync';
  }).length;
  useEffect(function () {
    var fetchData = /*#__PURE__*/function () {
      var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
        var result, _listDataSet$current$, conditionList, orderList, searchId;

        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _context.next = 2;
                return listDataSet.query();

              case 2:
                result = _context.sent;

                if (!result.length) {
                  _context.next = 14;
                  break;
                }

                _listDataSet$current$ = listDataSet.current.toData(), conditionList = _listDataSet$current$.conditionList, orderList = _listDataSet$current$.orderList, searchId = _listDataSet$current$.searchId;
                setListValue(searchId);
                dataSet.setQueryParameter('search', searchCode);
                _context.next = 9;
                return setCondition(dataSet, conditionList);

              case 9:
                _context.next = 11;
                return setOrder(dataSet, orderList);

              case 11:
                dataSet.query();
                _context.next = 16;
                break;

              case 14:
                setListValue(undefined);
                dataSet.query();

              case 16:
              case "end":
                return _context.stop();
            }
          }
        }, _callee);
      }));

      return function fetchData() {
        return _ref.apply(this, arguments);
      };
    }();

    fetchData();
  }, []);
  useEffect(function () {
    if (listDataSet.length) {
      var _listDataSet$current$2 = listDataSet.current.toData(),
          searchId = _listDataSet$current$2.searchId;

      setListValue(searchId);
    } else {
      setListValue(null);
    }
  }, [syncDataLength]);
  /**
   * 搜索配置弹窗
   * @param modalType
   */

  function handleOpenModal(modalType) {
    setType(modalType); // 新建配置，重置查询参数

    if (modalType === 'create') {
      listDataSet.create({
        searchCode: searchCode
      }, 0);
    }

    _Modal.open(_objectSpread(_objectSpread({
      okText: '保存',
      key: modalKey,
      title: '搜索配置',
      className: 'search-modal',
      closable: true,
      style: {
        width: 800
      }
    }, modalProps), {}, {
      children: /*#__PURE__*/React.createElement(SearchModal, {
        tableDataSet: dataSet,
        searchCode: searchCode,
        searchId: listValue,
        fields: fields,
        ignoreFields: ignoreFields,
        listDataSet: listDataSet,
        noSort: noSort,
        noQuery: noQuery,
        noCondition: noCondition,
        type: modalType
      }),
      onClose: cancelClose
    }));
  }
  /**
   * 关闭弹窗
   * 重置查询条件并查询table
   */


  function cancelClose() {
    listDataSet.remove(listDataSet.filter(function (record) {
      return record.status === 'add';
    }));
    setType(undefined);
  }

  function resetParams() {
    var queryDataSet = dataSet.queryDataSet || dataSet.props.queryDataSet;
    if (queryDataSet) queryDataSet.reset();

    var _listDataSet$current$3 = listDataSet.current.toData(),
        conditionList = _listDataSet$current$3.conditionList,
        orderList = _listDataSet$current$3.orderList;

    setCondition(dataSet, conditionList, true);
    setOrder(dataSet, orderList, true);
  }

  function handleChange(_x) {
    return _handleChange.apply(this, arguments);
  }

  function _handleChange() {
    _handleChange = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(value) {
      return _regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              setListValue(value); // 重置查询参数

              _context3.next = 3;
              return resetParams();

            case 3:
              if (!value) {
                dataSet.query();
              } else {
                listDataSet.map( /*#__PURE__*/function () {
                  var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(record) {
                    var _record$toData, conditionList, orderList;

                    return _regeneratorRuntime.wrap(function _callee2$(_context2) {
                      while (1) {
                        switch (_context2.prev = _context2.next) {
                          case 0:
                            if (!(record.get('searchId') === value)) {
                              _context2.next = 8;
                              break;
                            }

                            listDataSet.locate(record.index);
                            _record$toData = record.toData(), conditionList = _record$toData.conditionList, orderList = _record$toData.orderList;
                            _context2.next = 5;
                            return setCondition(dataSet, conditionList);

                          case 5:
                            _context2.next = 7;
                            return setOrder(dataSet, orderList);

                          case 7:
                            dataSet.query();

                          case 8:
                            return _context2.abrupt("return", null);

                          case 9:
                          case "end":
                            return _context2.stop();
                        }
                      }
                    }, _callee2);
                  }));

                  return function (_x2) {
                    return _ref2.apply(this, arguments);
                  };
                }());
              }

            case 4:
            case "end":
              return _context3.stop();
          }
        }
      }, _callee3);
    }));
    return _handleChange.apply(this, arguments);
  }

  function handleDelete() {
    return _handleDelete.apply(this, arguments);
  }

  function _handleDelete() {
    _handleDelete = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4() {
      var res, _listDataSet$current$4, conditionList, orderList;

      return _regeneratorRuntime.wrap(function _callee4$(_context4) {
        while (1) {
          switch (_context4.prev = _context4.next) {
            case 0:
              _context4.next = 2;
              return resetParams();

            case 2:
              _context4.next = 4;
              return listDataSet.delete(listDataSet.current, '是否删除本条搜索模板？');

            case 4:
              res = _context4.sent;

              if (_isEmpty(res)) {
                _context4.next = 16;
                break;
              }

              _context4.next = 8;
              return listDataSet.query();

            case 8:
              if (!listDataSet.length) {
                _context4.next = 15;
                break;
              }

              _listDataSet$current$4 = listDataSet.current.toData(), conditionList = _listDataSet$current$4.conditionList, orderList = _listDataSet$current$4.orderList;
              dataSet.setQueryParameter('search', searchCode);
              _context4.next = 13;
              return setCondition(dataSet, conditionList);

            case 13:
              _context4.next = 15;
              return setOrder(dataSet, orderList);

            case 15:
              dataSet.query();

            case 16:
            case "end":
              return _context4.stop();
          }
        }
      }, _callee4);
    }));
    return _handleDelete.apply(this, arguments);
  }

  var classString = classNames(styles['search-list-wrap'], _defineProperty({}, styles['search-list-wrap-border'], border));
  return /*#__PURE__*/React.createElement("div", {
    className: "".concat(className, " ").concat(classString)
  }, /*#__PURE__*/React.createElement("span", {
    className: styles['sl-tip']
  }, "\u67E5\u770B\u5217\u8868"), /*#__PURE__*/React.createElement(_Select, {
    searchable: true,
    value: listValue,
    onChange: handleChange
  }, _map(listDataSet.toData(), function (data) {
    return /*#__PURE__*/React.createElement(Option, {
      value: data.searchId
    }, data.searchName);
  })), /*#__PURE__*/React.createElement(_Button, {
    funcType: "flat",
    icon: "add_task",
    onClick: function onClick() {
      return handleOpenModal('create');
    }
  }, "\u65B0\u5EFA"), /*#__PURE__*/React.createElement(_Button, {
    funcType: "flat",
    icon: "mode_edit",
    disabled: !listValue,
    onClick: function onClick() {
      return handleOpenModal('edit');
    }
  }, "\u7F16\u8F91"), !noCopy && /*#__PURE__*/React.createElement(_Button, {
    funcType: "flat",
    icon: "baseline-file_copy",
    disabled: !listValue,
    onClick: function onClick() {
      return handleOpenModal('copy');
    }
  }, "\u590D\u5236"), /*#__PURE__*/React.createElement(_Button, {
    color: "red",
    funcType: "flat",
    icon: "delete",
    disabled: !listValue,
    onClick: function onClick() {
      return handleDelete();
    }
  }, "\u5220\u9664"), !noQuery && listValue && /*#__PURE__*/React.createElement(QueryBar, {
    type: type,
    searchId: listValue
  }));
});
export default SearchList;